import sys
import cv2


def delay_key(i):
    key = cv2.waitKey(i)
    if key == ord('q'):
        cv2.destroyAllWindows()
        sys.exit(0)
    elif key == ord('p'):
        key = cv2.waitKey(0)
        while key != ord('c'):
            if key == ord('q'):
                cv2.destroyAllWindows()
                sys.exit(0)
            key = cv2.waitKey(0)


def take_photo():
    # 打开摄像头
    cap = cv2.VideoCapture(1)
    count = 1

    while (True):
        # 开始用摄像头读数据，返回hx为true则表示读成功，frame为读的图像
        hx, frame = cap.read()

        # 如果hx为Flase表示开启摄像头失败，那么就输出"read vido error"并退出程序
        if hx is False:
            # 打印报错
            print('read video error')
            # 退出程序
            exit(0)

        # 显示摄像头图像，其中的video为窗口名称，frame为图像
        cv2.imshow('video', frame)

        key = cv2.waitKey(1) & 0xFF
        # 监测键盘输入是否为q，为q则退出程序
        if key == ord('s'):
            cv2.imwrite("./back/image_{}.jpg".format(count), frame)
            print("ok {}".format(count))
            count = count + 1
        elif key == ord('q'):
            break

        elif key == ord('p'):
            while True:
                key = cv2.waitKey(1) & 0xFF
                if key == ord('q'):
                    cap.release()
                    cv2.destroyAllWindows()
                    return 1
                elif key == ord('c'):
                    break

    cap.release()
    cv2.destroyAllWindows()


def photo_view():
    # 打开摄像头
    cap = cv2.VideoCapture(1)
    count = 1

    while (True):
        # 开始用摄像头读数据，返回hx为true则表示读成功，frame为读的图像
        hx, frame = cap.read()

        # 如果hx为Flase表示开启摄像头失败，那么就输出"read vido error"并退出程序
        if hx is False:
            # 打印报错
            print('read video error')
            # 退出程序
            exit(0)

        # 显示摄像头图像，其中的video为窗口名称，frame为图像
        cv2.imshow('video', frame)

        key = cv2.waitKey(100) & 0xFF
        if key == ord('q'):
            break
        else:
            cv2.imwrite('./back/image_{}.jpg'.format(count), frame)
            count += 1
            print("ok{}".format(count))

    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    photo_view()
